package com.ruiysoft.controller.upload.pic;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created by 化增光 on 2019/1/30.
 */
@Service
public class QinuService {
    //构造一个带指定Zone对象的配置类
    Configuration cfg = new Configuration(Zone.zone0());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    String accessKey = "cd49_Oa7kxvx8ebzyqSQmBG8ISYTJTp5Vi6e284t";
    String secretKey = "3WJoNPdOGHDiFCzV358uPqiBozEo0bKjEel94t8h";
    String bucket = "shop";

    Auth auth = Auth.create(accessKey, secretKey);

    //String localFilePath = "/Users/liudh/Desktop/WechatIMG383.jpeg";
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    String key = null;

    public Response upload(MultipartFile file) throws IOException {
        String upToken = auth.uploadToken(bucket);
        return uploadManager.put(file.getInputStream(), key, upToken,null,null);
    }

    public String upload(byte[] bytes) throws IOException {
        String upToken = auth.uploadToken(bucket);
        Response response = uploadManager.put(bytes, key, upToken);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(JSON.toJSONString(putRet));
        StringBuffer sb = new StringBuffer();
        sb.append("http://media.avicyt.com/").append(putRet.key);
        return sb.toString();
    }
}
